import React from 'react'
import {Button, Descriptions, InputNumber, Modal, Popconfirm, Select, Table, Tabs} from "antd";
import {defaultAvatarSrc} from "../../../component/CusomHeader/CusomHeader";
import moment from "moment";
import UserModel from "../../../model/user";
import Tags from "../user-list/tags";
import Info from "../../../service/info";
import log from "../../../service/log";
import {couponOption} from "./add-coupon-modal";

const {TabPane,} = Tabs
const {Item,} = Descriptions
const { Option } = Select

// const couponOption = {
//     '-1': '金币',
//     '1': 'UFO',
//     '2': '冲天火箭',
//     '3': '超级跑车',
//     '4': '双彩虹',
//     '5': '82年雪碧',
//     '6': '玫瑰花',
//     '7': '棒棒糖',
//     '8': '赞',
//     '10001': '预测免费卷',
//     '20001': '免费改名',
// }


const GiftMapper = {
    'gift_9': {
        name: '爱心',
        price: 1,
    },
    'gift_23': {
        name: '穿越时空',
        price: 28888,
    },
    'gift_24': {
        name: '海鲸之梦',
        price: 18888,
    },
    'gift_27': {
        name: '海洋之心',
        price: '5888',
    },
    'gift_28': {
        name: '真爱之吻',
        price: 8888,
    },
    'gift_29': {
        name: '真爱之吻',
        price: 3888,
    },
    'gift_30': {
        name: '蓝色妖姬',
        price: 7888,
    },
    'gift_31': {
        name: '在一起',
        price: 588,
    },
    'gift_32': {
        name: '独角兽',
        price: 5888,
    },
    'gift_34': {
        name: '梦幻城堡',
        price: 88888,
    },
    'gift_35': {
        name: '紫水晶',
        price: 38888,
    },
    'gift_36': {
        name: '疯狂泡泡机',
        price: 388,
    },
    'gift_37': {
        name: '月下告白',
        price: 1314,
    },
    'gift_38': {
        name: '钞票机',
        price: 28,
    },
    'gift_39': {
        name: '七彩祥云',
        price: 58,
    },
    'gift_40': {
        name: '哆啦A梦',
    },
    'gift_41': {
        name: '爱的告白',
        price: 188,
    },
    'gift_42': {
        name: '生日蛋糕',
        price: 288,
    },
    'gift_43': {
        name: '520',
        price: 520,
    },
    'gift_44': {
        name: '一吻定情',
        price: 888,
    },
    'gift_45': {
        name: '浪漫秋千',
        price: 999,
    },
    'gift_46': {
        name: '求婚',
        price: 1314,
    },
    'gift_47': {
        name: '爱的单车',
        price: 1888,
    },
    'gift_48': {
        name: '完美恋人',
        price: 3888,
    },
    'gift_49': {
        name: '梦幻天鹅湖',
        price: 3888,
    },
    'gift_50': {
        name: 'LOVE之心',
        price: 5200,
    },
    'gift_51': {
        name: '浪漫灯塔',
        price: 5888,
    },
    'gift_52': {
        name: '车队',
        price: 5888,
    },
}

const tags = Tags.map((tag, i) => ({title: tag, index: i,}))


class UserDetailModal extends React.Component {

    constructor(props) {
        super(props)
        this.model = new UserModel()
        this.tags = tags

        this.state = {
            deposit: [],
            fuwu: [],
            jinbi: [],
            daoju: [],
            jubao: [],
            userTags: [],
            newUserTags: [],
            coupon: null,
            couponCount: 0,
        }
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (this.props.visible && prevProps.visible === false) {
            setTimeout(() => {
                this.setState({
                    newUserTags: this.markToTags(this.props.user.Mark)
                })
            }, 0)
        }
    }

    fuwu = () => {
        const user = this.props.user
        const id = user.Id
        this.model
            .fuwu({id,})
            .then((res) => {
                const fuwu = res.data.ok
                if (fuwu) {
                    this.setState({
                        fuwu,
                    })
                }
            })
    }

    jinbi = () => {
        const user = this.props.user
        const id = user.Id
        this.model
            .jinbi({id,})
            .then((res) => {
                const jinbi = res.data.ok
                if (jinbi) {
                    this.setState({
                        jinbi,
                    })
                }
            })
    }

    daoju = () => {
        const user = this.props.user
        const id = user.Id
        this.model
            .daoju({id,})
            .then((res) => {
                const daoju = res.data
                if (daoju) {
                    this.setState({
                        daoju: daoju.d1,
                    })
                }
            })
    }

    deposit = () => {
        const user = this.props.user
        const id = user.Id
        this.model
            .deposit({id,})
            .then((res) => {
                const deposit = res.data.ok
                if (deposit) {
                    this.setState({
                        deposit,
                    })
                }
            })
    }

    jubao = () => {
        const user = this.props.user
        const id = user.Id
        this.model
            .jubao({id,})
            .then((res) => {
                const jubao = res.data.ok
                if (jubao.length === 0) {
                    this.setState({
                        jubao: null,
                    })
                } else {
                    this.setState({
                        jubao,
                    })
                }
            })
    }

    changeStatus = (id, status) => {
        this.model
            .status({
                id, status,
            })
            .then((res) => {
                if (res.data.ok) {
                    Info.success('修改用户状态成功')
                }
                this.props.setUserDetail({
                    ...this.props.user,
                    Status: status,
                })

            })
    }

    addCoupon = () => {
        const uid = this.props.user.Id
        const propid = this.state.coupon.value
        const propnum = this.state.couponCount
        this.model
            .addCoupon({uid, propid, propnum,})
            .then(resp => {
                const r = resp.data.ok
                if (r === 1) {
                    Info.success('添加成功')
                } else {
                    Info.error('添加失败')
                }
            })
            .then(() => {
                this.setState({
                    couponCount: 0,
                    modal: {
                        addCoupon: false,
                    }
                })
            })
            .then(() => {
                this.props.fetchAll()
            })
    }

    tagsToMark = (tags) => {

        let mark = 0
        for (let i = 0; i < tags.length; i++) {
            let value = tags[i].value
            mark += 1 << value
        }
        return mark

    }

    markToTags = (mark) => {

        const m = mark
        const b = m.toString(2)
        const l = Tags.length
        let markString = ''
        if (l > b.length) {
            markString += '0'.repeat(l - b.length)
            markString += b
        } else {
            markString = b
        }

        // const mark = user.U.Mark.toString(2).split().reverse().join()
        const arr = []
        markString = markString.split('').reverse().join('')
        for (let i = 0; i < markString.length; i++) {
            let char = markString[i]
            if (Number(char) === 1) {
                let key = i
                let value = i
                let label = Tags[i]
                arr.push({key, value, label,})
            }
        }
        return arr

    }

    setTags = () => {
        const tags = this.state.newUserTags
        let uid = this.props.user.Id
        let mark = this.tagsToMark(tags)
        this.model
            .setTag({mark, uid,})
            .then(resp => {
                if (resp.data.ok === 1) {
                    Info.success('修改标签成功')
                }
            })
            .then(() => {
                this.props.fetchAll()
            })
    }

    onUserTabClick = (key, index) => {
        if (key === '2') {
            this.deposit()
        }
    }

    onZhijinTabClick = (key) => {
        // const id = this.state.user.U.Id
        this[key]()
    }

    onCouponSelectChange = value => {
        log(value)
        this.setState({coupon: value,})
    }

    onTagSelectChange = (value) => {
        this.setState({newUserTags: value,})
    }

    renderUserDetail = (user) => {
        const detail = user
        if (detail) {
            console.log(detail)
            const icon = detail.Iconurl
            const nickname = detail.Nickname
            const username = detail.Username
            const isVip = detail.Vip > 0
            const src = detail.Usource
            const srcM = {
                1001: 'IOS',
                2001: '安卓',
                3001: 'H5',
            }
            const status = detail.Status
            const statusM = {
                1: '正常',
                2: '被监控',
                3: '黑名单',
            }

            return <Descriptions bordered column={4}>
                <Item label="用户" span={4}>
                    <div style={{display: 'flex'}}>
                        <img alt='' src={icon ? icon : defaultAvatarSrc} style={{height: '40px', width: '40px', marginRight: '8px',}}/>
                        <div>
                            <p style={{display: 'block',}}>用户名: {username}</p>
                            <span style={{display: 'block',}}>昵称: {nickname}</span>
                            <span>{detail.Id}</span>
                        </div>
                    </div>
                </Item>
                <Item label="注册时间" span={2}>{detail.Createt}</Item>
                <Item label="最后登陆" span={2}>{detail.Lastlogin}</Item>
                <Item label="会员等级">{detail.Viplevel}</Item>
                <Item label="金币">{detail.Gold}</Item>
                <Item label="是否vip">{isVip ? `${detail.Vip}天` : '否'}</Item>
                <Item label="最后充值时间">{detail.Vipst === 0 ? '无充值' : moment(new Date(detail.Vipst * 1000)).format('YYYY/MM/DD hh:mm')}</Item>
                <Item label="手机号">{detail.Mobile}</Item>
                <Item label="真实姓名">{detail.Realname}</Item>
                <Item label="身份证号" span={2}>{detail.Idnumber}</Item>
                <Item label="邀请码">{detail.Yqcode}</Item>
                <Item label="填写邀请码">{detail.Usedyqcode}</Item>
                <Item label="来源">{srcM[src]}</Item>
                <Item label="状态">
                    <span style={{marginRight: '8px',}}>
                        {statusM[status]}
                    </span>

                    <Popconfirm title={'确定拉黑？'} onConfirm={() => this.changeStatus(detail.Id, 3)}>
                        <Button style={{marginRight: '8px',}}>拉黑</Button>
                    </Popconfirm>
                    <Popconfirm title={'确定监控？'} onConfirm={() => this.changeStatus(detail.Id, 2)}>
                        <Button style={{marginRight: '8px',}}>监控</Button>
                    </Popconfirm>
                    <Popconfirm title={'确定恢复正常？'} onConfirm={() => this.changeStatus(detail.Id, 1)}>
                        <Button>恢复</Button>
                    </Popconfirm>
                </Item>
                <Item label="优惠卷" span={4}>
                    {this.renderJuan(detail.Packet)}
                    <Select
                        labelInValue
                        style={{width: '100%',}}
                        placeholder="选择优惠卷"
                        onChange={this.onCouponSelectChange}
                    >
                        {Object.keys(couponOption).map((c, index) => <Option
                            value={Number(c)}
                            key={index}
                        >{couponOption[c]}</Option>)}
                    </Select>
                    <InputNumber
                        style={{marginTop: 8, marginRight: 8, width: 150,}}
                        placeholder='优惠卷数量'
                        onChange={e => this.setState({couponCount: e,})}
                        value={this.state.couponCount}
                    />

                    <Button onClick={this.addCoupon}>确认添加</Button>
                </Item>
                <Item label="用户标签" span={4}>
                    <Select
                        mode="multiple"
                        labelInValue
                        style={{ width: '80%' }}
                        placeholder="用户标签"
                        value={this.state.newUserTags}
                        onChange={this.onTagSelectChange}
                    >
                        {this.tags.map(tag => {
                            return <Option value={tag.index} key={tag.index}>{tag.title}</Option>
                        })}
                    </Select>
                    <Button
                        onClick={this.setTags}
                    >保存</Button>
                </Item>
                <Item label="举报内容" span={4}>
                    <Button onClick={this.jubao}>获取举报内容</Button>
                    {this.state.jubao === null
                        ? <span>无举报内容</span>
                        : this.state.jubao.map(item => <p>{item.Hftxt}</p>)
                    }
                </Item>
            </Descriptions>
        }

        return null
    }

    renderDeposit = (user) => {
        const {deposit, fuwu, jinbi, daoju,} = this.state
        const noColObj = {
            title: '交易编号',
            dataIndex: 'Dealno',
            render: this.defaultColRender,
        }

        const pingtaiColObj = {
            title: '平台',
            dataIndex: 'Paytype',
            render: text => {
                if (text === 1) return '安卓'
                if (text === 2) return 'ios'
                if (text === 3) return 'h5'
            },
        }

        const moneyColObj = {
            title: '价格',
            dataIndex: 'Money',
            render: this.defaultColRender
        }

        const gold = {
            title: '金币',
            dataIndex: 'Gold',
            render: this.defaultColRender
        }

        const total = {
            title: '充值后金币',
            dataIndex: 'Total',
            render: this.defaultColRender
        }
        const state = {
            title: '状态',
            dataIndex: 'State',
            render: (text) => text === 2 ? '已支付' : '未支付',
        }
        const creatT = {
            title: '交易时间',
            dataIndex: 'CreateT',
            render: this.defaultColRender,
        }
        const mark = {
            title: 'Mark',
            dataIndex: 'Mark',
            render: this.defaultColRender,
        }

        const cost = {
            title: '花费',
            dataIndex: 'Cost',
            render: this.defaultColRender,
        }

        const propId = {
            title: '道具',
            dataIndex: 'Propid',
            render: id => couponOption[id]
        }

        const pingtai = {
            title: '平台',
            dataIndex: 'Anchorname',
            render: this.defaultColRender,
        }

        const game = {
            title: '赛事',
            dataIndex: 'Game',
            render: this.defaultColRender,
        }

        const cols1 = [
            noColObj,
            pingtaiColObj,
            moneyColObj,
            gold,
            total,
            state,
            creatT,
            mark,
        ]

        const cols2 = [
            noColObj,
            pingtaiColObj,
            moneyColObj,
            gold,
            total,
            state,
            creatT,
            mark,
        ]

        const cols3 = [
            noColObj,
            cost,
            propId,
            pingtai,
            game,
            creatT,
        ]

        const cols4 = [
            noColObj,
            cost,
            propId,
            pingtai,
            game,
            creatT,
        ]

        return <Tabs onTabClick={(key) => this.onZhijinTabClick(key)}>
            <TabPane key='deposit' tab='金币充值'>
                <Table
                    dataSource={deposit}
                    columns={cols1}
                    rowKey={(record, index) => index}
                />
            </TabPane>
            <TabPane key='fuwu' tab='服务消费'>
                <Table
                    dataSource={fuwu}
                    columns={cols2}
                    rowKey={(record, index) => index}
                />
            </TabPane>
            <TabPane key='jinbi' tab='金币使用'>
                <Table
                    dataSource={jinbi}
                    columns={cols3}
                    rowKey={(record, index) => index}
                />
            </TabPane>
            <TabPane key='daoju' tab='道具使用'>
                <Table
                    dataSource={daoju}
                    columns={cols4}
                    rowKey={(record, index) => index}
                />
            </TabPane>
        </Tabs>
    }

    renderJuan = (string) => {
        if (string) {
            const list = JSON.parse(string)
            // [[8,20],[7,20],[6,20],[20001,1]]
            let str = ''
            list.map(([id, count,]) => {
                let name = String(couponOption[String(id)])
                if (name === 'undefined') {
                    name = GiftMapper[`gift_${id}`]?.name
                }
                if (name) {
                    str += `${name} x ${count}`
                    str += ' '
                }
            })

            return str
        }
        return []
    }

    render() {
        const v = this.props.visible
        const u = this.props.user
        const userModal = <Modal
            width='100%'
            title="查看用户"
            visible={v}
            footer={null}
            maskClosable={true}
            onCancel={this.props.onCancel}
            destroyOnClose={true}
            rowKey={(record, index) => index}
        >
            <Tabs
                defaultActiveKey="1"
                onTabClick={(tab, index) => this.onUserTabClick(tab, index)}
            >
                <TabPane tab="个人信息" key="1">
                    {this.renderUserDetail(u)}
                </TabPane>
                <TabPane tab="资金明细" key="2">
                    {this.renderDeposit(u)}
                </TabPane>
            </Tabs>

        </Modal>
        return userModal
    }

}

export default UserDetailModal